package com.binance.gateway.filter.auth;

import com.binance.gateway.app.base.helper.BaseHelper;
import com.binance.gateway.app.constant.Constant;
import com.binance.gateway.constant.GwFilterOrders;
import com.binance.gateway.util.URIUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.regex.Pattern;

@Component
@Slf4j
public class PrepareFilter extends ZuulFilter {
    private Pattern startAuthUrlPattern = Pattern.compile("^(/(gateway-api|exchange-api)/).*$");
    @Resource
    private BaseHelper baseHelper;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return GwFilterOrders.AUTH;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        String uri = URIUtil.normalize(ctx.getRequest());
        return startAuthUrlPattern.matcher(uri).matches();

    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.addZuulRequestHeader(Constant.HEADER_BASE_URL, baseHelper.getBasePath(ctx.getRequest()));
        return null;
    }
}
